import { BaseService, CoolCommException } from '@cool-midway/core';
import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, Repository } from 'typeorm';
import {
  DemandTeamRequestEntity,
  DemandTeamRequestStatus,
} from '../entity/request';
import {
  ProviderUpdateDemandStatusDTO,
  SubmitDemandRequestDTO,
} from '../dto/request';
import { ProviderProfileEntity } from '../../provider/entity/profile';
import { CapacityEntity } from '../../transport/entity/capacity';
import { ProviderTeamEntity } from '../../provider/entity/team';

export interface DemandRequestPageQuery extends Record<string, any> {
  page?: number;
  size?: number;
  order?: string;
  sort?: string;
  keyWord?: string;
  status?: number | string;
}
export type DemandRequestPagePayload =
  | DemandRequestPageQuery
  | {
    query?: DemandRequestPageQuery;
  };

@Provide()
export class DemandRequestService extends BaseService {
  @InjectEntityModel(DemandTeamRequestEntity)
  demandRequestEntity: Repository<DemandTeamRequestEntity>;

  @InjectEntityModel(ProviderProfileEntity)
  providerProfileEntity: Repository<ProviderProfileEntity>;

  @InjectEntityModel(CapacityEntity)
  capacityEntity: Repository<CapacityEntity>;

  @InjectEntityModel(ProviderTeamEntity)
  providerTeamEntity: Repository<ProviderTeamEntity>;

  @InjectEntityModel(ProviderTeamEntity)
  teamModel: Repository<ProviderTeamEntity>;

  /**
   * 用户提交需求
   */
  async submit(userId: number, dto: SubmitDemandRequestDTO) {
    const team = await this.getTeamByProviderId(dto.providerId);

    const entity = this.demandRequestEntity.create({
      userId,
      teamId: team.id,
      ownerProviderId: team.ownerProviderId,
      description: dto.description,
      contactName: dto.contactName,
      contactInfo: dto.contactInfo,
      status: DemandTeamRequestStatus.PENDING,
    });

    return await this.demandRequestEntity.save(entity);
  }

  /**
   * 团队分页查看需求
   */
  async pageByTeam(teamId: number, query: DemandRequestPagePayload) {
    const resolvedQuery = this.resolvePageQuery(query);
    const qb = this.demandRequestEntity
      .createQueryBuilder('a')
      .where('a.teamId = :teamId', { teamId })
      .orderBy('a.id', 'DESC');

    const statusFilter = resolvedQuery?.status;
    if (
      statusFilter !== undefined &&
      statusFilter !== null &&
      statusFilter !== ''
    ) {
      const parsed = Number(statusFilter);
      if (Number.isNaN(parsed)) {
        throw new CoolCommException('状态参数不合法');
      }
      qb.andWhere('a.status = :status', { status: parsed });
    }

    const result = await this.entityRenderPage(qb, resolvedQuery ?? {});
    result.list = this.normalizeRawRows(result.list);
    return result;
  }

  /**
   * 根据团队ID获取需求信息
   */
  async infoByTeam(teamId: number, id: number) {
    const qb = this.demandRequestEntity
      .createQueryBuilder('a')
      .where('a.teamId = :teamId', { teamId })
      .andWhere('a.id = :id', { id })
      .orderBy('a.id', 'DESC');
    return await qb.getOne();
  }

  /**
   * 更新需求状态
   */
  async updateStatus(
    teamId: number,
    providerId: number,
    dto: ProviderUpdateDemandStatusDTO
  ) {
    const exist = await this.demandRequestEntity.findOne({
      where: { id: Equal(dto.requestId), teamId: Equal(teamId) },
    });
    if (!exist) {
      throw new CoolCommException('需求不存在或无权操作');
    }

    exist.status = dto.status;
    exist.providerRemark = dto.providerRemark ?? exist.providerRemark;
    exist.lastOperatorProviderId = providerId;
    await this.demandRequestEntity.save(exist);
  }
  /**
   * 普通用户分页查看自己的需求
   */
  async pageByUser(userId: number, query: DemandRequestPagePayload) {
    const resolvedQuery = this.resolvePageQuery(query);
    const qb = this.demandRequestEntity
      .createQueryBuilder('a')
      .where('a.userId = :userId', { userId })
      .orderBy('a.id', 'DESC');

    const statusFilter = resolvedQuery?.status;
    if (
      statusFilter !== undefined &&
      statusFilter !== null &&
      statusFilter !== ''
    ) {
      const parsed = Number(statusFilter);
      if (Number.isNaN(parsed)) {
        throw new CoolCommException('状态参数不合法');
      }
      qb.andWhere('a.status = :status', { status: parsed });
    }

    const result = await this.entityRenderPage(qb, resolvedQuery ?? {});
    result.list = this.normalizeRawRows(result.list);
    return result;
  }

  /**
   * 普通用户查看需求详情
   */
  async detailByUser(userId: number, requestId: number) {
    const exist = await this.demandRequestEntity.findOne({
      where: { id: Equal(requestId), userId: Equal(userId) },
    });
    if (!exist) {
      throw new CoolCommException('需求不存在或无权查看');
    }
    return exist;
  }

  private async getTeamByProviderId(providerId: number) {
    const profile = await this.providerProfileEntity.findOne({
      where: { providerId: Equal(providerId) },
    });
    if (!profile) {
      throw new CoolCommException('目标服务人员不存在');
    }

    let teamId = profile.teamId;
    if (!teamId) {
      const team = await this.teamModel.findOne({ where: { ownerProviderId: Equal(providerId) } });
      teamId = team?.id;
    }

    if (!teamId) {
      throw new CoolCommException('该服务人员尚未加入任何团队');
    }

    const team = await this.providerTeamEntity.findOne({
      where: { id: Equal(teamId) },
    });
    if (!team) {
      throw new CoolCommException('团队不存在或已被删除');
    }
    return team;
  }

  private normalizeRawRows(rows: any[] = []) {
    return rows.map(row => {
      const formatted = {};
      Object.keys(row).forEach(key => {
        const normalizedKey = key.replace(/^[a-z]+_/, '');
        formatted[normalizedKey] = row[key];
      });
      return formatted;
    });
  }

  private resolvePageQuery(payload?: DemandRequestPagePayload): DemandRequestPageQuery {
    if (!payload) {
      return {};
    }
    const maybeWrapped = (payload as any).query;
    if (maybeWrapped && typeof maybeWrapped === 'object') {
      return maybeWrapped as DemandRequestPageQuery;
    }
    return payload as DemandRequestPageQuery;
  }
}


